package glog

import (
	"io"
	"os"

	"github.com/sirupsen/logrus"
	"gopkg.in/natefinch/lumberjack.v2"
)

var log logrus.Logger

var (
	Trace = log.Trace
	Debug = log.Debug
	Info  = log.Info
	Warn  = log.Warn
	Error = log.Error

	Tracef = log.Tracef
	Debugf = log.Debugf
	Infof  = log.Infof
	Warnf  = log.Warnf
	Errorf = log.Errorf
)

const (
	TraceLevel = Level(logrus.TraceLevel)
	DebugLevel = Level(logrus.DebugLevel)
	InfoLevel  = Level(logrus.InfoLevel)
	WarnLevel  = Level(logrus.WarnLevel)
	ErrorLevel = Level(logrus.ErrorLevel)
)

type Level logrus.Level
type LoggerConfig = lumberjack.Logger

func InitLog(level Level, filename string, maxSize, maxAge, maxBackups int) {
	InitLogger(level, &LoggerConfig{
		Filename:   filename,
		MaxSize:    maxSize,
		MaxAge:     maxAge,
		MaxBackups: maxBackups,
		LocalTime:  false,
		Compress:   true,
	})
}

func InitLogger(level Level, config *LoggerConfig) {
	log = *logrus.New()

	// 设置日志级别
	// logger.SetLevel(logrus.DebugLevel)
	log.SetLevel(logrus.Level(level))

	// 自定义格式
	log.SetFormatter(&logrus.TextFormatter{
		TimestampFormat: "2006-01-02 15:04:05",
	})

	// 同时输出到文件和终端
	multiWriter := io.MultiWriter(os.Stdout, config)

	log.SetOutput(multiWriter)
}
